﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using static LiWi.Shell;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;

namespace LiWiTools
{
    public partial class UserControlSecend : UserControl
    {
        Data IPName;
        int nowAxis = 0;
        public static bool upView = false;    //创建表格状态
        bool registFlag = false;//锁存开启状态
        bool hwpsFlag = false;  //位置比较状态
        bool connectAxis = false;//同步运动状态
        int op = 0;             //位置比较输出口
        int state = 0;          //位置比较输出状态
        bool enable=false;      //轴使能状态

        public UserControlSecend(Data IP )
        {
            InitializeComponent();
            IPName = IP;
            //禁用第一行第一列编辑
            dataAxisView.CellBeginEdit += DataGridView_CellBeginEdit;
            //更改表格对应参数修改
            dataAxisView.CellValueChanged += DataGridView_CellValueChange;
            selectRegistMode.SelectedIndex = 1;
        }

        ~UserControlSecend()
        {
            PMC_HwPswitch2(IPName.handle, nowAxis, 2, op, state, 0, 0, 0, 0);
            PMC_HwTimer(IPName.handle, 0, 0, 0, 0, 0, 0);  //先关闭
        }

        /// <summary>
        /// 禁用行列编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex == 0 || e.RowIndex == 12) e.Cancel = true;
        }

        //更改表格数据
        private void DataGridView_CellValueChange(object sender, DataGridViewCellEventArgs e)
        {
          
                Task.Run(() =>
                {
                    Thread.Sleep(100);
                    int idle = 0;
                    PMC_GetIfIdle(IPName.handle, nowAxis, ref idle);
                    if (idle != 0)
                    {
                        Thread.Sleep(200);
                        DataGridView view = sender as DataGridView;
                        //获取更改的单元格的行列索引
                        int rowIndex = e.RowIndex;
                        int columnIndex = e.ColumnIndex;
                        if (rowIndex >= 0 && columnIndex >= 1)
                        {
                            //获取更改后的值
                            object newValue = view.Rows[rowIndex].Cells[columnIndex].Value;
                            //columnIndex -= 1;
                            try
                            {
                                switch (rowIndex)
                                {
                                    case 0:     //轴类型
                                        PMC_SetAtype(IPName.handle, nowAxis, Convert.ToInt32(newValue));
                                        ToolsForm.dataAxis[IPName].axisType[nowAxis] = Convert.ToInt32(newValue);
                                        break;
                                    case 1:     //脉冲当量
                                        PMC_SetUnits(IPName.handle, nowAxis, Convert.ToSingle(newValue));
                                        ToolsForm.dataAxis[IPName].units[nowAxis] = Convert.ToSingle(newValue);
                                        break;
                                    case 2:     //开始速度
                                        PMC_SetLspeed(IPName.handle, nowAxis, Convert.ToSingle(newValue));
                                        ToolsForm.dataAxis[IPName].startSpeed[nowAxis] = Convert.ToSingle(newValue);
                                        break;
                                    case 3:     //速度
                                        PMC_SetSpeed(IPName.handle, nowAxis, Convert.ToSingle(newValue));
                                        ToolsForm.dataAxis[IPName].runSpeed[nowAxis] = Convert.ToSingle(newValue);
                                        break;
                                    case 4:     //加速度
                                        PMC_SetAccel(IPName.handle, nowAxis, Convert.ToSingle(newValue));
                                        ToolsForm.dataAxis[IPName].accel[nowAxis] = Convert.ToSingle(newValue);
                                        break;
                                    case 5:     //减速度
                                        PMC_SetDecel(IPName.handle, nowAxis, Convert.ToSingle(newValue));
                                        ToolsForm.dataAxis[IPName].decel[nowAxis] = Convert.ToSingle(newValue);
                                        break;
                                    case 6:     //快速减速度
                                        PMC_SetFastDec(IPName.handle, nowAxis, Convert.ToSingle(newValue));
                                        ToolsForm.dataAxis[IPName].fastDec[nowAxis] = Convert.ToSingle(newValue);
                                        break;
                                    case 7:     //正向软限位
                                        PMC_SetFsLimit(IPName.handle, nowAxis, Convert.ToSingle(newValue));
                                        ToolsForm.dataAxis[IPName].fsLimit[nowAxis] = Convert.ToSingle(newValue);
                                        break;
                                    case 8:     //负向软限位
                                        PMC_SetRsLimit(IPName.handle, nowAxis, Convert.ToSingle(newValue));
                                        ToolsForm.dataAxis[IPName].rsLimit[nowAxis] = Convert.ToSingle(newValue);
                                        break;
                                    case 9:     //原点
                                        PMC_SetDatumIn(IPName.handle, nowAxis, Convert.ToInt32(newValue));
                                        ToolsForm.dataAxis[IPName].datumIO[nowAxis] = Convert.ToInt32(newValue);
                                        break;
                                    case 10:   //正限位
                                        PMC_SetFwdIn(IPName.handle, nowAxis, Convert.ToInt32(newValue));
                                        ToolsForm.dataAxis[IPName].fwdIO[nowAxis] = Convert.ToInt32(newValue);
                                        break;
                                    case 11:    //负限位
                                        PMC_SetRevIn(IPName.handle, nowAxis, Convert.ToInt32(newValue));
                                        ToolsForm.dataAxis[IPName].revIO[nowAxis] = Convert.ToInt32(newValue);
                                        break;
                                    case 13:    //DPOS
                                        PMC_SetDpos(IPName.handle, nowAxis, Convert.ToSingle(newValue));
                                        break;
                                    case 14:    //MPOS
                                        PMC_SetMpos(IPName.handle, nowAxis, Convert.ToSingle(newValue));
                                        break;
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                    }
                });            
        }




        /// <summary>
        /// 更新轴参数
        /// </summary>
        /// <param name="axisNum">轴号</param>
        public async Task UpAxisData(int axisNum)
        {
            nowAxis = axisNum;
            dataAxisView.Columns.Clear();
            dataAxisView.Rows.Clear();
            //dataAxisView.ReadOnly = true;
            dataAxisView.Columns.Add("param", "轴参数");
            dataAxisView.Columns.Add("AxisNum", $"Axis{axisNum}");
            //列表数据
            string[] paramenters = new string[] {
                 "轴类型","脉冲当量","起始速度", "运行速度","加速度","减速度","快速减速度",
                "正向软限位", "负向软限位","原点IO","正限位IO","负限位IO","报警信息","DPOS","MPOS","IDLE","MTYPE"
            };
            foreach (string param in paramenters)
            {
                int rowIndex = dataAxisView.Rows.Add();
                dataAxisView.Rows[rowIndex].Cells[0].Value = param;
            }
            object[] value = { ToolsForm.dataAxis[IPName].axisType[nowAxis],ToolsForm.dataAxis[IPName].units[nowAxis],
                ToolsForm.dataAxis[IPName].startSpeed[nowAxis], ToolsForm.dataAxis[IPName].runSpeed[nowAxis],
                ToolsForm.dataAxis[IPName].accel[nowAxis],ToolsForm.dataAxis[IPName].decel[nowAxis],
                ToolsForm.dataAxis[IPName].fastDec[nowAxis],(double)ToolsForm.dataAxis[IPName].fsLimit[nowAxis],
                (double)ToolsForm.dataAxis[IPName].rsLimit[nowAxis],ToolsForm.dataAxis[IPName].datumIO[nowAxis],
                ToolsForm.dataAxis[IPName].fwdIO[nowAxis],ToolsForm.dataAxis[IPName].revIO[nowAxis],
                ToolsForm.dataAxis[IPName].errAxisMes[nowAxis],ToolsForm.dataAxis[IPName].dPos[nowAxis],
                ToolsForm.dataAxis[IPName].mPos[nowAxis],ToolsForm.dataAxis[IPName].idle[nowAxis],
                ToolsForm.dataAxis[IPName].mtype[nowAxis]};
            //添加数据
            for (int j = 0; j < value.Length; j++)
            {
                dataAxisView.Rows[j].Cells[1].Value = value[j].ToString();
            }
            //禁用排列
            dataAxisView.AllowUserToOrderColumns = false;
            foreach (DataGridViewColumn column in dataAxisView.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            upView = true;
            //回原
            toolTip1.SetToolTip(linkModeMessage,
                "模式0：清除所有轴的错误状态(清除AXISSTATUS的找原点中状态)\r\n" +
                "模式1：轴以爬行速度往正方向回原直到 Z 信号出现\r\n" +
                "模式2：轴以爬行速度往负方向回原直到 Z 信号出现\r\n" +
                "模式3：轴以速度正常速度正方向移动，碰到原点然后以爬行速度反向运动直至离开原点\r\n" +
                "模式4：轴以速度正常速度反方向移动，碰到原点然后以爬行速度正向运动直至离开原点\r\n" +
                "模式5：轴以正常速度正方向移动，直至碰到原点IO，然后以爬行速度离开原点，再继续以爬行速度反转直到碰到 Z 信号\r\n" +
                "模式6：轴以正常速度反方向移动，直至碰到原点IO，然后以爬行速度离开原点，再继续以爬行速度反转直到碰到 Z 信号\r\n" +
                "模式8：轴以正常速度正方向移动，直至碰到原点IO\r\n" +
                "模式9：轴以正常速度反方向移动，直至碰到原点IO");
            toolTip2.SetToolTip(link_AtypeMessage,
                "0：虚拟轴\r\n" +
                "1：脉冲方向方式的步进或伺服\r\n" +
                "2：模拟信号控制方式的伺服\r\n" +
                "3：正交编码器\r\n" +
                "4：脉冲方向输出+正交编码器输入\r\n" +
                "5：脉冲方向输出+脉冲方向编码器输入\r\n" +
                "6： 脉冲方向方式的编码器\r\n" +
                "7： 脉冲方向方式步进或伺服+EZ信号输入\r\n" +
                "8： CAN扩展脉冲方向方式步进或伺服\r\n" +
                "9： CAN扩展正交编码器\r\n" +
                "10： CAN扩展脉冲方向方式的编码器\r\n" +
                "65： ECAT周期位置模式，需支持EtherCAT\r\n" +
                "66： ECAT周期速度模式，需支持EtherCAT\r\n" +
                "67： ECAT周期力矩模式，需支持EtherCAT");

            //获取回原数据
            PMC_GetFwdIn(IPName.handle, nowAxis, ref ToolsForm.dataAxis[IPName]._hardFwdIN);
            PMC_GetRevIn(IPName.handle, nowAxis, ref ToolsForm.dataAxis[IPName]._hardRevIN);
            //设置反找等待时间
            PMC_GetHomeWait(IPName.handle, nowAxis, ref ToolsForm.dataAxis[IPName]._waitCT);
            //设置爬行速度
            PMC_GetCreep(IPName.handle, nowAxis, ref ToolsForm.dataAxis[IPName]._creep);
            //设置零点信号
            PMC_GetDatumIn(IPName.handle, nowAxis, ref ToolsForm.dataAxis[IPName]._homeIN);
            comfwdin.Text = ToolsForm.dataAxis[IPName]._hardFwdIN.ToString();
            comrevin.Text = ToolsForm.dataAxis[IPName]._hardRevIN.ToString();
            combhomein.Text = ToolsForm.dataAxis[IPName]._homeIN.ToString();
            numwaitCT.Text = ToolsForm.dataAxis[IPName]._waitCT.ToString();
            numcreep.Text = ToolsForm.dataAxis[IPName]._creep.ToString();

            //单轴运动
            PMC_GetSpeed(IPName.handle, nowAxis, ref ToolsForm.dataAxis[IPName].runSpeed[nowAxis]);
            PMC_GetAccel(IPName.handle, nowAxis, ref ToolsForm.dataAxis[IPName].accel[nowAxis]);
            PMC_GetDecel(IPName.handle, nowAxis, ref ToolsForm.dataAxis[IPName].decel[nowAxis]);
            PMC_GetUnits(IPName.handle, nowAxis, ref ToolsForm.dataAxis[IPName].units[nowAxis]);
            numSpeed.Value = (decimal)ToolsForm.dataAxis[IPName].runSpeed[nowAxis];
            numAccel.Value = (decimal)ToolsForm.dataAxis[IPName].accel[nowAxis];
            numDecel.Value = (decimal)ToolsForm.dataAxis[IPName].decel[nowAxis];
            numUnint.Value = (decimal)ToolsForm.dataAxis[IPName].units[nowAxis];

            //同步运动
            for (int i = 0; i < ToolsForm.dataControl[IPName].axisVirtuAxises; i++)
            {
               if(i!=nowAxis) comAxisMove.Items.Add(i);
            }
            comAxisMove.Text=comAxisMove.Items[0].ToString();
        }

        /// <summary>
        /// 回原
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btngohome_Click(object sender, EventArgs e)
        {
            if (enable)
            {
                btngohome.Text = "回原中";
                groupBox1.Enabled = false;
                groupBox2.Enabled = false;
                ToolsForm.dataAxis[IPName]._model = Convert.ToInt32(commodel.Text);             //回原模式                
                ToolsForm.dataAxis[IPName]._goBackModel = chkGoBack.Checked ? 1 : 0;               //限位反找开关
                if (ToolsForm.dataAxis[IPName]._goBackModel == 1) ToolsForm.dataAxis[IPName]._model = Convert.ToInt32(commodel.Text) + 10;
                else ToolsForm.dataAxis[IPName]._model = Convert.ToInt32(commodel.Text);
                //PMC_SetAxisEnable(Data.handle, nowAxis, 1);


                ToolsForm.dataAxis[IPName]._hardFwdIN = Convert.ToInt32(comfwdin.Text);

                ToolsForm.dataAxis[IPName]._hardRevIN = Convert.ToInt32(comrevin.Text);

                ToolsForm.dataAxis[IPName]._homeIN = Convert.ToInt32(combhomein.Text);

                ToolsForm.dataAxis[IPName]._waitCT = Convert.ToInt32(numwaitCT.Text);

                ToolsForm.dataAxis[IPName]._creep = Convert.ToSingle(numcreep.Text);


                //设置限位
                PMC_SetFwdIn(IPName.handle, nowAxis, ToolsForm.dataAxis[IPName]._hardFwdIN);
                PMC_SetRevIn(IPName.handle, nowAxis, ToolsForm.dataAxis[IPName]._hardRevIN);
                //设置反找等待时间
                PMC_SetHomeWait(IPName.handle, nowAxis, ToolsForm.dataAxis[IPName]._waitCT);
                //设置爬行速度
                PMC_SetCreep(IPName.handle, nowAxis, ToolsForm.dataAxis[IPName]._creep);
                //设置零点信号
                PMC_SetDatumIn(IPName.handle, nowAxis, ToolsForm.dataAxis[IPName]._homeIN);
                //单轴回原
                PMC_Single_Datum(IPName.handle, nowAxis, ToolsForm.dataAxis[IPName]._model);

                Thread thsport = new Thread(() =>
                {
                    var a = 0;
                    PMC_GetIfIdle(IPName.handle, nowAxis, ref a);
                    while (a == 0)
                    {
                        PMC_GetIfIdle(IPName.handle, nowAxis, ref a);
                        Thread.Sleep(50);
                    }


                    this.Invoke(new Action(() =>
                    {
                        btngohome.Text = "回原";
                        groupBox1.Enabled = true;
                        groupBox2.Enabled = true;
                    }));
                });
                thsport.Start();
            }
            else MessageBox.Show("请先对轴使能");
        }

        private void Btnstop_Click(object sender, EventArgs e)
        {
            PMC_Rapidstop(IPName.handle, 3);            
            btngohome.Text = "回原";
            btnMove.Text = "启动";
            groupBox1.Enabled = true;
            groupBox2.Enabled = true;
            #region 锁存
            registFlag = false;
            button_regist.Text = "开启锁存";
            selectRegistMode.Enabled = true;
            cheregistContinue.Enabled = true;
            labregistState.Text = "未锁存";
            labregistPoint.Text = "0.00";
            #endregion
            #region 比较输出
            btn_HwPs2.Text = "开启位置比较";
            PMC_HwPswitch2(IPName.handle, nowAxis, 2, op, state, 0, 0, 0, 0);
            PMC_HwTimer(IPName.handle, 0, 0, 0, 0, 0, 0);  //先关闭
            hwpsFlag = false;
            #endregion
        }

        private void Btnzero_Click(object sender, EventArgs e)
        {
            PMC_SetDpos(IPName.handle, nowAxis, 0);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (enable)
            {
                btnMove.Text = "启动中";
                groupBox1.Enabled = false;
                groupBox2.Enabled = false;
                int[] axislist = { nowAxis };
                float[] goValue = { (float)numGoPoint.Value };
                PMC_SetSpeed(IPName.handle, nowAxis, (float)numSpeed.Value);
                PMC_SetAccel(IPName.handle, nowAxis, (float)numAccel.Value);
                PMC_SetDecel(IPName.handle, nowAxis, (float)numDecel.Value);
                PMC_SetUnits(IPName.handle, nowAxis, (float)numUnint.Value);
                if (radrunMove1.Checked) PMC_Move(IPName.handle, 1, axislist, goValue);
                else PMC_MoveAbs(IPName.handle, 1, axislist, goValue);
                Thread thsport = new Thread(() =>
                {
                    var a = 0;
                    PMC_GetIfIdle(IPName.handle, nowAxis, ref a);
                    while (a == 0)
                    {
                        PMC_GetIfIdle(IPName.handle, nowAxis, ref a);
                        Thread.Sleep(50);
                    }
                    this.Invoke(new Action(() =>
                    {
                        btnMove.Text = "启动";
                        groupBox1.Enabled = true;
                        groupBox2.Enabled = true;
                    }));
                });
                thsport.Start();
            }
            else MessageBox.Show("请先对轴使能");
        }

       
        private void btnGoBack_MouseDown(object sender, MouseEventArgs e)
        {
            if (enable)
            {
                PMC_SetSpeed(IPName.handle, nowAxis, (float)numSpeed.Value);
                PMC_SetAccel(IPName.handle, nowAxis, (float)numAccel.Value);
                PMC_SetDecel(IPName.handle, nowAxis, (float)numDecel.Value);
                PMC_SetUnits(IPName.handle, nowAxis, (float)numUnint.Value);
                int[] axisnum = { nowAxis };
                PMC_Base(IPName.handle, 1, axisnum);
                PMC_Single_Vmove(IPName.handle, nowAxis, -1);           //连续运动：1正向，-1负向
            }
            else MessageBox.Show("请先对轴使能");
        }

        private void btnGoAhead_MouseDown(object sender, MouseEventArgs e)
        {
            if (enable)
            {
                PMC_SetSpeed(IPName.handle, nowAxis, (float)numSpeed.Value);
                PMC_SetAccel(IPName.handle, nowAxis, (float)numAccel.Value);
                PMC_SetDecel(IPName.handle, nowAxis, (float)numDecel.Value);
                PMC_SetUnits(IPName.handle, nowAxis, (float)numUnint.Value);
                int[] axisnum = { nowAxis };
                PMC_Base(IPName.handle, 1, axisnum);
                PMC_Single_Vmove(IPName.handle, nowAxis, 1);           //连续运动：1正向，-1负向
            }
            else MessageBox.Show("请先对轴使能");
        }

        private void btnGoBack_MouseUp(object sender, MouseEventArgs e)
        {
            PMC_Rapidstop(IPName.handle, 3);
        }

        private void btnGoAhead_MouseUp(object sender, MouseEventArgs e)
        {
            PMC_Rapidstop(IPName.handle, 3);
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (IPName.handle != IntPtr.Zero)
            {
                if (upView)
                {
                    //PMC_GetDpos(IPName.handle,nowAxis,ref dPos);
                    //PMC_GetMpos(IPName.handle, nowAxis, ref mPos);
                    //更新表格
                    object[] value = {  ToolsForm.dataAxis[IPName].axisType[nowAxis], ToolsForm.dataAxis[IPName].units[nowAxis],
                         ToolsForm.dataAxis[IPName].startSpeed[nowAxis],  ToolsForm.dataAxis[IPName].runSpeed[nowAxis],
                         ToolsForm.dataAxis[IPName].accel[nowAxis], ToolsForm.dataAxis[IPName].decel[nowAxis], ToolsForm.dataAxis[IPName].fastDec[nowAxis],
                    (double) ToolsForm.dataAxis[IPName].fsLimit[nowAxis],(double) ToolsForm.dataAxis[IPName].rsLimit[nowAxis],
                        ToolsForm.dataAxis[IPName].datumIO[nowAxis], ToolsForm.dataAxis[IPName].fwdIO[nowAxis], 
                        ToolsForm.dataAxis[IPName].revIO[nowAxis], ToolsForm.dataAxis[IPName].errAxisMes[nowAxis],
                        ToolsForm.dataAxis[IPName].dPos[nowAxis],ToolsForm.dataAxis[IPName].mPos[nowAxis],ToolsForm.dataAxis[IPName].idle[nowAxis],
                        ToolsForm.dataAxis[IPName].mtype[nowAxis]};
                    //添加数据
                    for (int j = 0; j < value.Length; j++)
                    {
                        dataAxisView.Rows[j].Cells[1].Value = value[j].ToString();
                    }

                    //更新点位            
                    dpos.Text =ToolsForm.dataAxis[IPName].dPos[nowAxis].ToString();
                    //正负原点限位
                    uint rev = 0, fwd = 0, datum = 0;
                    PMC_GetIn(IPName.handle, ToolsForm.dataAxis[IPName].revIO[nowAxis], ref rev);
                    PMC_GetIn(IPName.handle, ToolsForm.dataAxis[IPName].fwdIO[nowAxis], ref fwd);
                    PMC_GetIn(IPName.handle, ToolsForm.dataAxis[IPName].datumIO[nowAxis], ref datum);
                    if (rev != 0) labRev.BackColor = Color.Green;
                    else labRev.BackColor = Color.DarkGray;
                    if (fwd != 0) labFwd.BackColor = Color.Green;
                    else labFwd.BackColor = Color.DarkGray;
                    if (datum != 0) labDamu.BackColor = Color.Green;
                    else labDamu.BackColor = Color.DarkGray;

                    if (hwpsFlag)
                    {
                        uint opstate = 0;

                        PMC_GetOp(IPName.handle, op, ref opstate);
                        if (opstate == 1) lab_OPState.BackColor = Color.Green;
                        else lab_OPState.BackColor = Color.DarkGray;
                    }
                }
            }

        }

        private void button_regist_Click(object sender, EventArgs e)
        {
            if (!registFlag)
            {
                registFlag = true;
                button_regist.Text = "关闭锁存";
                selectRegistMode.Enabled = false;
                cheregistContinue.Enabled = false;

                int mode = 0;
                mode = selectRegistMode.SelectedIndex;
                Task.Factory.StartNew(() =>
                {

                    if (cheregistContinue.Checked)
                    {
                        int tableStart = 0;
                        int tableNum = 10;
                        float[] registNum = { -1 }; 
                        float[] setStart = { -1,-1,-1,-1,-1, -1, -1, -1, -1, -1,-1 };
                        PMC_SetTable(IPName.handle, tableStart, tableNum, setStart);
                        while (registFlag)
                        {
                            float[] pos = { 0 };

                            if (mode <= 4) mode += 100;
                            PMC_CycleRegist(IPName.handle, nowAxis, mode,tableStart,tableNum);      
                            while ( registFlag == true)
                            {
                                PMC_GetTable(IPName.handle, tableStart, 1, registNum);
                                if (registNum[0] > 0)
                                {
                                    PMC_GetTable(IPName.handle, Convert.ToInt32(registNum[0]), 1, pos);
                                    labregistState.Invoke(new Action(() =>
                                    {
                                        labregistState.Text = "已锁存";
                                    }));
                                    labregistPoint.Invoke(new Action(() =>
                                    {
                                        labregistPoint.Text = pos[0].ToString();
                                    }));
                                }
                                if (!registFlag)
                                    return;
                            }
                            
                        }
                    }
                    else
                    {
                        int mark = 0;
                        int markB = 0;
                        float pos = 0;
                        float posB = 0;
                        PMC_Regist(IPName.handle, nowAxis, mode);
                        while (mark == 0 && markB == 0 && registFlag == true)
                        {
                            if (mode <= 4) PMC_GetMark(IPName.handle, nowAxis, ref mark);
                            else PMC_GetMarkB(IPName.handle, nowAxis, ref markB);
                            if (!registFlag)
                                return;
                        }
                        labregistState.Invoke(new Action(() =>
                        {
                            labregistState.Text = "已锁存";
                        }));
                        if (mark != 0)
                        {
                            PMC_GetRegPos(IPName.handle, nowAxis, ref pos);
                            labregistPoint.Invoke(new Action(() =>
                            {
                                labregistPoint.Text = pos.ToString();
                            }));
                        }
                        if (markB != 0)
                        {
                            PMC_GetRegPosB(IPName.handle, nowAxis, ref posB);
                            labregistPointB.Invoke(new Action(() =>
                            {
                                labregistPointB.Text = posB.ToString();
                            }));
                        }

                        this.Invoke(new Action(() =>
                        {
                            registFlag = false;
                            button_regist.Text = "开启锁存";
                            selectRegistMode.Enabled = true;
                            cheregistContinue.Enabled = true;
                        }));
                    }
                });

            }
            else
            {
                registFlag = false;
                button_regist.Text = "开启锁存";
                selectRegistMode.Enabled = true;
                cheregistContinue.Enabled = true;
                labregistState.Text = "未锁存";
                labregistPoint.Text = "0.00";
            }
        }

        private void btn_HwPs2_Click(object sender, EventArgs e)
        {

            if (!hwpsFlag)
            {
                btn_HwPs2.Text = "关闭位置比较";
                op = Convert.ToInt32(com_OP.Text);
                state = check_FirstState.Checked ? 1 : 0;
                float point1 = Convert.ToSingle(num_Point1.Value);
                float point2 = Convert.ToSingle(num_Point2.Value);
                float[] point = { point1, point2 };
                PMC_SetVectorMoved(IPName.handle, nowAxis, 0);
                PMC_SetTable(IPName.handle, 0, 2, point);
                PMC_SetAtype(IPName.handle, nowAxis, 1);
                PMC_HwPswitch2(IPName.handle, nowAxis, 2, op, state, 0, 0, 0, 0);
                PMC_HwPswitch2(IPName.handle, nowAxis, 1, op, state, 0, 1, 2, 0);
                //PMC_HwTimer(IPName.handle, 0, 0, 0, 0, 0, 0);  //先关闭
                //PMC_HwTimer(IPName.handle, 2, 100000, 50000, 1, 0, 1);
                hwpsFlag = true;
            }
            else
            {
                btn_HwPs2.Text = "开启位置比较";
                PMC_HwPswitch2(IPName.handle, nowAxis, 2, op, state, 0, 0, 0, 0);
                PMC_HwTimer(IPName.handle, 0, 0, 0, 0, 0, 0);  //先关闭
                hwpsFlag = false;
            }
        }

        /// <summary>
        /// 启动同步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click_1(object sender, EventArgs e)
        {
            int axisMove=0;
            if (!connectAxis)
            {
                axisMove = Convert.ToInt32(comAxisMove.Text);
                float mag = Convert.ToSingle(numMag.Value);
                PMC_Connect(IPName.handle, mag, axisMove, nowAxis);
                button1.Text = "关闭同步";
                connectAxis = true;
            }
            else
            {
                button1.Text = "启动同步";
                PMC_Single_Cancel(IPName.handle, axisMove, 2);
                connectAxis = false;
            }

        }

        private void btn_enable_Click(object sender, EventArgs e)
        {
            if (!enable)
            {
                btn_enable.Text = "关闭使能";
                PMC_SetAxisEnable(IPName.handle, nowAxis, 1);
                btn_enable.BackColor = Color.Green;
                enable = true;
            }
            else
            {
                btn_enable.Text = "开启使能";
                PMC_SetAxisEnable(IPName.handle, nowAxis, 0);
                btn_enable.BackColor = Color.White;
                enable = false;
            }
        }

        private void btn_StartGoBack_Click(object sender, EventArgs e)
        {
            if (enable)
            {
                btn_StartGoBack.Text = "启动中";
                btn_StartGoBack.Enabled = false;
                groupBox1.Enabled = false;
                groupBox2.Enabled = false;
                btnMove.Enabled = false;
                int[] axislist = { nowAxis };
                float[] goValue = { (float)numGoEnd.Value };
                PMC_SetSpeed(IPName.handle, nowAxis, (float)numSpeed.Value);
                PMC_SetAccel(IPName.handle, nowAxis, (float)numAccel.Value);
                PMC_SetDecel(IPName.handle, nowAxis, (float)numDecel.Value);
                PMC_SetUnits(IPName.handle, nowAxis, (float)numUnint.Value);
                float[] moveLine= { Convert.ToSingle( numGoStart.Value),Convert.ToSingle(numGoEnd.Value) };
                int[] axis = { 0,1,2 };
                float[] line1 = { Convert.ToSingle(numGoStart.Value) ,Convert.ToSingle(numGoStart.Value) ,Convert.ToSingle(numGoStart.Value) };
                float[] line2= { Convert.ToSingle(numGoEnd.Value), Convert.ToSingle(numGoEnd.Value), Convert.ToSingle(numGoEnd.Value) };

                PMC_Single_MoveAbs(IPName.handle, nowAxis, moveLine[0]);                
                for (int i = 0; i < num_Num.Value; i++)
                {
                    PMC_Single_MoveAbs(IPName.handle, nowAxis, moveLine[1]);
                    PMC_Single_MoveAbs(IPName.handle, nowAxis, moveLine[0]);
                    if (num_WaitTime.Value>0)
                    {
                        int idle = 0;
                        while (idle == 0)
                        {                            
                            PMC_GetIfIdle(IPName.handle, nowAxis, ref idle);
                            Thread.Sleep(10);
                        }
                        Thread.Sleep(Convert.ToInt32(num_WaitTime.Value));
                    }
                    
                }
                this.Invoke(new Action(() =>
                {
                    btn_StartGoBack.Text = "启动";
                    btn_StartGoBack.Enabled = true;
                    groupBox1.Enabled = true;
                    groupBox2.Enabled = true;
                    btnMove.Enabled = true;
                }));


            }
            else MessageBox.Show("请先对轴使能");
        }
    }
}
